using UnityEngine;
using System.Collections;

public class SpriteManipulate : MonoBehaviour {
	
	public tk2dSprite sprite;
	public UISprite spriteNGUI;
	Color originalColor;
	public bool isPanelManipulate;
	bool bInit;

	void Awake () 
	{

	}

	void InitSprite()
	{
		if(bInit)
			return;
		bInit = true;
		if(sprite==null)
		{
			sprite = gameObject.GetComponent<tk2dSprite>();
			if(sprite)
				originalColor = sprite.color;
		}
		if(spriteNGUI==null)
		{
			spriteNGUI = gameObject.GetComponentInChildren<UISprite>();
			if(spriteNGUI)
				originalColor = spriteNGUI.color;
		}
	}

	void SetColor(Color color)
	{
		if(sprite)
			sprite.color = color;
		else
			spriteNGUI.color = color;
	}
	
	Color GetColor()
	{
		if(sprite)
			return sprite.color;
		else
			return spriteNGUI.color;		
	}
	
	public void SetPanelManipulate()
	{
		isPanelManipulate = true;
	}
	
	public void SetSpriteName(string name)
	{
		InitSprite();
		glog.debug("spritename = "+name);
		if(sprite)
		{
			sprite.SetSprite(name);
		}
		else
		{
			IconOverheadNGUI icon = GetComponentInChildren<IconOverheadNGUI>();
			if(icon)
			{
				//string spriteName = "icon_item_" + name;
				//float scaleMod = 1.0f;
//				if(name.StartsWith("S_") )
//				{
//					scaleMod = 0.5f;
//					spriteName = name;
//				}
				spriteNGUI.spriteName = name;
				//icon.ResetScale(scaleMod);
			}
			else
				spriteNGUI.spriteName = name;
		}
	}
	
	public void ChangeAlphaDelay(float targetAlpha, float speed, float delay, bool bDestroy)
	{
		InitSprite();
		StartCoroutine(CoChangeAlpha(targetAlpha, speed, delay, bDestroy));
	}
	
	public void ChangeAlpha(float targetAlpha, float speed, bool bDestroy)
	{
		ChangeAlphaDelay(targetAlpha,speed,0,bDestroy);
	}
	
	IEnumerator CoChangeAlpha(float targetAlpha, float speed, float delay, bool bDestroy)
	{
		yield return new WaitForSeconds(delay);
		originalColor = GetColor();
		float alpha_num = 1.0f;
		while(alpha_num>0)
		{
			alpha_num -= speed*Time.deltaTime;
			if(alpha_num <0)
				alpha_num = 0;
			SetColor ( new Color(originalColor.r, originalColor.g, originalColor.b, alpha_num) );
			yield return null;
		}		
		if(bDestroy)
			Destroy(gameObject);
	}

}
